package com.zx.callback.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.zx.callback.common.alipay.AlipayTradeState;
import com.zx.callback.common.ex.DaoException;
import com.zx.callback.common.properties.AlipayConfig;
import com.zx.callback.po.CouponInfo;
import com.zx.callback.po.OrderInfo;
import com.zx.callback.po.PayThirdTrade;
import com.zx.callback.service.CouponInfoService;
import com.zx.callback.service.OrderOperService;
import com.zx.callback.service.OrderSearchService;
import com.zx.callback.service.PayOrderService;
import com.zx.callback.vo.JsonResult;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author ：yanst
 * @since: 2017/11/22
 * @history：(date editor desc)
 */
@RequestMapping("zhifu/notifyUrl")
@Controller
public class NotifyUrlController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private PayOrderService payOrderService;
    @Resource
    private OrderSearchService orderSearchService;
    @Resource
    private OrderOperService orderOperService;
    @Resource
    private CouponInfoService couponInfoService;

    @RequestMapping("aliWapPay")
    @ResponseBody
    public void aliWapPay(HttpServletRequest request, HttpServletResponse response) {
        try {
            //获取支付宝POST过来反馈信息
            Map<String,String> params = setMap(request);
            logger.debug("支付宝异步通知商户执行中,返回参数：{}", JSON.toJSONString(params));

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
            //交易状态
            String app_id = new String(request.getParameter("app_id").getBytes("ISO-8859-1"),"UTF-8");

            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
            //计算得出通知验证结果
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
            if (signVerified) {//验证失败
                logger.error("验签失败，params={}", JSON.toJSONString(params));
                response.getWriter().write("failure");
            }

            if(!AlipayConfig.app_id.equals(app_id)){
                logger.error("支付宝app_id不匹配，params={}", JSON.toJSONString(params));
                response.getWriter().write("failure");
            }

            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

            //判断该笔订单是否在商户网站中已经做过处理
            //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
            //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
            //如果有做过处理，不执行商户的业务程序
            /** 验证交易信息 */
            JsonResult<PayThirdTrade> jsonResult = payOrderService.validNotifyUrlForAlipay(params);
            if (jsonResult.getCode() != 0){
                response.getWriter().write("failure");
            }
            PayThirdTrade payThirdTrade = jsonResult.getT();
            /** 验证订单是否存在 、是否已经付款*/
            JsonResult<OrderInfo> jsonResultOrderInfo = orderSearchService.validOrderIsPay(payThirdTrade.getOrderNo());
            if (jsonResult.getCode() != 0){
                response.getWriter().write("failure");
            }
            OrderInfo orderInfo = jsonResultOrderInfo.getT();

            /** 更改优惠卷为已经使用 */
            if(payThirdTrade != null && StringUtils.isNotBlank(payThirdTrade.getMemo()) && !"null".equals(payThirdTrade.getMemo())){
                couponInfoService.userCoupon(Long.valueOf(payThirdTrade.getMemo()));

                CouponInfo couponInfo = couponInfoService.detail(Long.valueOf(payThirdTrade.getMemo()));
                if (couponInfo != null){
                    orderInfo.setCouponMoney(couponInfo.getAmount());
                }else {
                    orderInfo.setCouponMoney(new BigDecimal("0.00"));
                }
                logger.info("使用优惠卷id:{}", payThirdTrade.getMemo());

            }
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            if (trade_status.equals(AlipayTradeState.TRADE_FINISHED)){//交易结束，不可退款
                //注意：
                //如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                //如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。

                //todo 结束交易没有告诉我是否需要进行后续处理
            } else if (trade_status.equals(AlipayTradeState.TRADE_SUCCESS)){//交易支付成功
                //注意：
                //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。

                /** 更改订单状态、更改交易状态 */
                JsonResult jsonResult1 = payOrderService.updatePayState(orderInfo, payThirdTrade, params);
                if (jsonResult1.getCode() == 0){
                    logger.error("支付宝异步通知成功");
                    response.getWriter().write("success");
                }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
    //            out.clear();
            //////////////////////////////////////////////////////////////////////////////////////////

            }
        }catch (AlipayApiException e){
            logger.error("支付宝支付异步通知出错，错误信息", e);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private Map<String,String> setMap(HttpServletRequest request){
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            params.put(name, valueStr);
        }
        return params;
    }

}
